<?php defined('BASEPATH') OR die('No direct access allowed.');
/**
 * Description of Services
 *
 * Created on Jan 12, 2011
 * @author Ramon Gutierrez
 * @copyright Bitstop Network Services Inc.
 * @version 0.1
 */
class Services extends Controller {
	function Services()	{
		parent::Controller();
		global $header, $data;
		
		// Check if user is logged in
		if(!$this->session->userdata('account_id') ||
		($this->session->userdata('account_type') != 'site_admin' && $this->session->userdata('account_type') != 'company')) {
			redirect(site_url(), 'refresh');
		}
		
		// Header variables
		$header['extras'] = "";
		$header['grid'] = false;
		$header['title'] = $this->lang->line('title_services');
		$data['module'] = 'services';
		
		// Include global models for this module
		$this->load->model('services_model');
	}
	
	function index() {
		global $header, $data;
		
		// Load grid helper
		$this->load->helper('flexigrid');
		
		// Template variables
		$header['grid'] = true;
							
		// Load up that header!
		$this->load->view('header', $header);
		
		// Load the sidebar
		$this->load->view('sidebar-left', $data);
		
		// Flexigrid stuff
		if($this->session->userdata('account_type') == 'site_admin') {
			$colModel['id'] = array('', 50, TRUE, 'left', 0);
			$colModel['title'] = array('Service', 345, TRUE, 'left', 2);
			$colModel['prefix'] = array('Prefix', 55, TRUE, 'left', 1);
			$colModel['name'] = array('Company', 255, TRUE, 'left', 1);
			$colModel['access'] = array('Is global?', 55, TRUE, 'center', 0);
			$colModel['actions'] = array('Actions', 100, FALSE, 'left', 0);
		} else {
			$colModel['id'] = array('', 50, TRUE, 'left', 0);
			$colModel['title'] = array('Service', 205, TRUE, 'left', 2);
			$colModel['prefix'] = array('Prefix', 55, TRUE, 'left', 1);
			$colModel['description'] = array('Description', 290, TRUE, 'left', 1);
			$colModel['actions'] = array('Actions', 100, FALSE, 'left', 0);
		}
		
		// Confirm Flexigrid parameters
		$gridParams = array(
							'width' => 'auto',
							'height' => 'auto',
							'rp' => 50,
							'rpOptions' => '[10,15,20,25,50]',
							'pagestat' => 'Displaying: {from} to {to} of {total} items.',
							'blockOpacity' => 0.5,
							'title' => "<' + 'img src=\"" . site_url('images/services.png') . "\" alt=\"\" /> Services",
							'showTableToggleBtn' => false
						   );
		
		// Create Flexigrid buttons
		$buttons[] = array('New Service', 'new', 'the_grid');
		$buttons[] = array('separator');
		$buttons[] = array('Select All', 'select', 'the_grid');
		$buttons[] = array('De-select All', 'deselect', 'the_grid');
		$buttons[] = array('separator');
		$buttons[] = array('Batch Edit', 'edit', 'the_grid');

		// Build the grid!
		$grid_js = build_grid_js('the_grid', site_url("ajax/services_getrows/" . ($this->session->userdata('account_type') == 'company' ? $this->session->userdata('client_id') : "")), $colModel, 'title', 'asc', $gridParams, $buttons);
		$data['the_grid'] = $grid_js;
		
		// Dish out the meat
		$this->load->view('grid-index', $data);
		
		// Let's see that footer!
		$this->load->view('footer');
	}
	
	function edit($items) {
		global $header, $data;
		
		// Build the ID array
		$item_array = array_unique(explode(":", $items));
		
		// Template variables
		$header['extras'] = '<script type="text/javascript">' . "\n" .
							'// <![CDATA[' . "\n" .
							'  $(document).ready(function() {' . "\n" .
							'    var options = {' . "\n" .
							'        target:         "#response",' . "\n" .
							'        success:        showResponse' . "\n" .
							'    };' . "\n\n" .
							'    $("#theform").ajaxForm(options);' . "\n" .
							'    function showResponse(responseText, statusText) {' . "\n" .
							'      $("#response").html(responseText).show();' . "\n" .
							'      if(responseText == "Update successful") {' . "\n" .
							'        $("#response").css("border", "1px solid #c8fb6e");' . "\n" .
							'        $("#response").css("backgroundColor", "#eaffb9");' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'        alert(responseText);' . "\n" .
							'        window.location = "' . site_url($data['module']) . '/";' . "\n" .
							'        //alert(responseText);' . "\n" .
							'      } else {' . "\n" .
							'        $("#response").css("border", "1px solid #fa4646");' . "\n" .
							'        $("#response").css("backgroundColor", "#fabfbf");' . "\n" .
							'        submitted = false;' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'      }' . "\n" .
							'    };' . "\n" .
							'  });' . "\n" .
							'// ]]>' . "\n" .
							'</script>' . "\n\n";
		
		// Load up that header!
		$this->load->view('header', $header);
		
		// Load the sidebar
		$this->load->view('sidebar-left', $data);
		
		// Load the first part of the edit section
		$data['subtitle'] = $this->lang->line('subtitle_edit_services');
		$this->load->view('edit-top', $data);
		
		// Initialize the idstring var
		$idstring = '';
		
		// Counter var
		$i = 1;

		// Generate editable blocks for each item
		foreach($item_array as $item) {
			// Gather item info
			$row1 = $this->common_model->getInfo($data['module'], $item);
			
			if($row1) {
				if($row1['access'] && $this->session->userdata('account_type') == 'company') {
					if($this->services_model->checkHasGlobal($item, $this->session->userdata('client_id'))) {
						$is_valid = true;
					} else {
						$is_valid = false;
					}
				} else {
					$is_valid = true;
				}
				
				if($is_valid) {
					if(($row1['access'] && $this->session->userdata('account_type') == 'company') || !$row1['access']) {
						if(!$row1['access']) {
							$row2 = $this->common_model->getInfo("clients_services", $row1['id'], "description", "service_id = " . $row1['id']);
						} else {
							$row2 = $this->common_model->getInfo("clients_services", $row1['id'], "description", "service_id = " . $row1['id'] . " AND client_id = " . $this->session->userdata('client_id'));
						}
					} else {
						$row2 = array();
					}
					
					// Merge both arrays
					$row = array_merge($row1, $row2);
				}
			} else {
				$row = false;
			}
			
			if($row) {
				// Get additional data
				$row['i'] = $i;
				$row['readonly'] = $this->session->userdata('account_type') == 'site_admin' || ($this->session->userdata('account_type') == 'company' && !$row['access']) ? "" : ' readonly="readonly" style="font-style: italic;"';
				
				if($row['closing_codes']) {
					$closing_codes = json_decode($row['closing_codes']);
					$codes = "";
					
					foreach($closing_codes as $code) {
						$codes .= $codes ? "\n$code" : $code;
					}
					
					$row['closing_codes'] = $codes;
				}
				
				// Get company name if admin
				if($this->session->userdata('account_type') == 'site_admin' || $row['access']) {
					$row['company'] = $row['access'] ? "[global service]" : $this->services_model->getCompany($row['id']);
				} 
				
				// Load the block
				$this->load->view('edit-row-services', $row);
					
				// Add to idstring
				$idstring .= ($idstring ? "," . $row['id'] : $row['id']);
				
				// Increment counter
				$i++;
			}
		}
		
		// If no IDs exist, redirect to list
		if(!$idstring) {
			redirect(site_url($data['module']), 'refresh');
		}
		
		// Load the second part of the edit section
		$this->load->view('edit-bottom', array('idstring' => base64_encode($idstring)));
		
		// Let's see that footer!
		$this->load->view('footer');
	}
	
	function edit_ajax() {
		global $data;
		
		// Set module
		$module = $data['module'];
		
		// Generate ID array
		$ids = explode(",", base64_decode($this->input->post("idstring")));
		$error = false;

		foreach($ids as $id) {
			$i = $this->input->post("i" . $id);
			if(is_numeric($id)) {
				if($this->common_model->exists($module, $id)) {
					$info = $this->common_model->getInfo($module, $id);
					$post = array();

					$post['title'] = $this->input->post("title" . $id);
					$post['prefix'] = $this->input->post("prefix" . $id);
					$post['description'] = $this->input->post("description" . $id);
					$post['closing_codes'] = $this->input->post("closing_codes" . $id);
					
					// Get additional info
					if(!$info['access'] || $this->session->userdata('account_type') == 'company') {
						if($info['access']) {
							$where = "cs.service_id = $id AND cs.client_id = " . $this->session->userdata('client_id');
						} else {
							$where = "cs.service_id = $id";
						}
						
						$info2 = $this->common_model->getInfo('clients_services cs, services s', $id, 'cs.id, cs.client_id', $where);
					}
					
					// Check for duplicates
					if($this->session->userdata('account_type') == 'site_admin') {
						if($info['access']) {
							$dupe_title = $this->db->select('id')->from('services')->where("id != $id AND title = '" . $post['title'] . "' AND access = 1")->get();
							$dupe_prefix = $this->db->select('id')->from('services')->where("id != $id AND prefix = '" . $post['prefix'] . "' AND access = 1")->get();
						} else {
							$dupe_title = $this->db->select('s.id')->from('services s, clients_services cs')->where("s.id != $id AND s.title = '" . $post['title'] . "' AND access = 0 AND s.id = cs.service_id AND cs.client_id = " . $info2['client_id'])->get();
							$dupe_prefix = $this->db->select('s.id')->from('services s, clients_services cs')->where("s.id != $id AND s.prefix = '" . $post['prefix'] . "' AND access = 0 AND s.id = cs.service_id AND cs.client_id = " . $info2['client_id'])->get();
						}
					} else {
						$dupe_title = $this->db->select('s.id')->from('services s, clients_services cs')->where("s.id != $id AND s.title = '" . $post['title'] . "' AND s.id = cs.service_id AND cs.client_id = " . $this->session->userdata('client_id'))->get();
						$dupe_prefix = $this->db->select('s.id')->from('services s, clients_services cs')->where("s.id != $id AND s.prefix = '" . $post['prefix'] . "' AND s.id = cs.service_id AND cs.client_id = " . $this->session->userdata('client_id'))->get();
					}

					$error .= !$post['title'] ? "<li>Enter a name for Service $i.</li>" : ($dupe_title->num_rows() > 0 ? "<li>Name is already in use for Service $i.</li>" : '');
					$error .= !$post['prefix'] ? "<li>Enter an identifying prefix for Service $i.</li>" : ($dupe_prefix->num_rows() > 0 ? "<li>Identifying prefix is already in use for Service $i.</li>" : '');
					$error .= !$post['description'] && (!$info['access'] || $this->session->userdata('account_type') == 'company') ? "<li>Enter a description for Service $i.</li>" : '';
					$error .= !$post['closing_codes'] ? "<li>Enter at least one closing code for Service $i.</li>" : '';

					if(!$error) {
						$post['closing_codes'] = json_encode(explode("\n", preg_replace("/[^a-zA-Z0-9\s]/", "", preg_replace('`[\r\n]+`', "\n", $post['closing_codes']))));
						
						$data = array(
									  'title' => $post['title'],
									  'prefix' => strtoupper($post['prefix']),
									  'closing_codes' => $post['closing_codes']
									 );
						
						if($this->session->userdata('account_type') == 'site_admin' || !$info['access']) {
							$query1 = $this->common_model->update($module, $id, $data);
						} else {
							$query1 = true;
						}

						if($query1) {
							if(isset($info2)) {
								$data = array(
											  'description' => $post['description'],
											  'changed' => 1
											 );

								$query2 = $this->common_model->update('clients_services', $info2['id'], $data);
							}
						} else {
							$error .= "<li>Whoops! Something seems to have gone wrong. Please try again later.</li>";
						}
					}
				}
			}
		}
		
		if($error) {
			echo "<b>Please correct the following errors:</b><br /><ul class='errors'>$error</ul>";
		} else {
			echo "Update successful";
		}
	}
	
	function create() {
		global $header, $data;
		
		// Template variables
		$header['extras'] = '<script type="text/javascript">' . "\n" .
							'// <![CDATA[' . "\n" .
							'  $(document).ready(function() {' . "\n" .
							'    var options = {' . "\n" .
							'        target:         "#response",' . "\n" .
							'        success:        showResponse' . "\n" .
							'    };' . "\n\n" .
							'    $("#theform").ajaxForm(options);' . "\n" .
							'    function showResponse(responseText, statusText) {' . "\n" .
							'      $("#response").html(responseText).show();' . "\n" .
							'      if(responseText == "Service has been created") {' . "\n" .
							'        $("#response").css("border", "1px solid #c8fb6e");' . "\n" .
							'        $("#response").css("backgroundColor", "#eaffb9");' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'        alert(responseText);' . "\n" .
							'        window.location = "' . site_url($data['module']) . '/";' . "\n" .
							'        //alert(responseText);' . "\n" .
							'      } else {' . "\n" .
							'        $("#response").css("border", "1px solid #fa4646");' . "\n" .
							'        $("#response").css("backgroundColor", "#fabfbf");' . "\n" .
							'        submitted = false;' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'      }' . "\n" .
							'    };' . "\n" .
							'  });' . "\n" .
							'// ]]>' . "\n" .
							'</script>' . "\n\n";
		
		// Load up that header!
		$this->load->view('header', $header);
		
		// Load the sidebar
		$this->load->view('sidebar-left', $data);
		
		// Get additional data
		if($this->session->userdata('account_type') == 'company') {
			$data['globals'] = $this->services_model->getGlobals();
		}
		
		// Dish out the meat
		$this->load->view('create-services', $data);
		
		// Let's see that footer!
		$this->load->view('footer');
	}
	
	function create_ajax() {
		global $data;
		
		// Set module
		$module = $data['module'];
		
		// Service info
		$post['globals'] = $this->input->post("globals");
		$post['title'] = $this->input->post("title");
		$post['prefix'] = $this->input->post("prefix");
		$post['description'] = $this->input->post("description");
		$post['closing_codes'] = $this->input->post("closing_codes");
		$post['access'] = $this->session->userdata('account_type') == 'site_admin' ? "1" : "0";
		$error = false;
		
		// Check for duplicates
		if($this->session->userdata('account_type') == 'site_admin') {
			$dupe_title = $this->db->select('id')->from('services')->where("title = '" . $post['title'] . "' AND access = 1")->get();
			$dupe_prefix = $this->db->select('id')->from('services')->where("prefix = '" . $post['prefix'] . "' AND access = 1")->get();
		} else {
			$dupe_title = $this->db->select('s.id')->from('services s, clients_services cs')->where("s.title = '" . $post['title'] . "' AND s.id = cs.service_id AND cs.client_id = " . $this->session->userdata('client_id'))->get();
			$dupe_prefix = $this->db->select('s.id')->from('services s, clients_services cs')->where("s.prefix = '" . $post['prefix'] . "' AND s.id = cs.service_id AND cs.client_id = " . $this->session->userdata('client_id'))->get();
		}
		
		// Check for errors
		$error .= !$post['title'] ? "<li>Enter a name for this service.</li>" : ($dupe_title->num_rows() > 0 ? "<li>Service name is already in use.</li>" : '');
		$error .= !$post['prefix'] ? "<li>Enter an identifying prefix for this service.</li>" : ($dupe_prefix->num_rows() > 0 ? "<li>Identifying prefix is already in use.</li>" : '');
		$error .= !$post['description'] && $this->session->userdata('account_type') == 'company' ? "<li>Enter a description for this service.</li>" : '';
		$error .= !$post['closing_codes'] ? "<li>Enter at least one closing code for this service.</li>" : '';

		if(!$error) {
			if($this->session->userdata('account_type') == 'site_admin' || !$post['globals']) {
				$post['closing_codes'] = json_encode(explode("\n", preg_replace("/[^a-zA-Z0-9\s]/", "", preg_replace('`[\r\n]+`', "\n", $post['closing_codes']))));
				
				$data = array(
							  'title' => $post['title'],
							  'prefix' => $post['prefix'],
							  'closing_codes' => $post['closing_codes'],
							  'access' => $post['access']
							 );
							 
				$query1 = $this->common_model->create('services', $data);
				$info['id'] = $query1;
			} else {
				$info = $this->common_model->getInfo($module, $post['globals'], 'id');
				
				$query1 = true;
			}
			
			if($query1) {
				if($this->session->userdata('account_type') == 'company') {
					$data = array(
								  'description' => $post['description'],
								  'service_id' => $info['id'],
								  'client_id' => $this->session->userdata('client_id')
								 );
					
					$query2 = $this->common_model->create('clients_services', $data);
				} else {
					$query2 = true;
				}
			}
			
			if(!$query1 || !$query2) {
				$error .= "<li>Whoops! Something seems to have gone wrong. Please try again later.</li>";
			}
		}
		
		if($error) {
			echo "<b>Please correct the following errors:</b><br /><ul class='errors'>$error</ul>";
		} else {
			echo "Service has been created";
		}
	}
	
	function del() {
		// Retrieve post var
		$id = $this->input->post("ids");

		// Get item info
		$info = $this->common_model->getInfo('services', $id, "title, access");

		if($info) {
			// Run the delete query
			if($this->session->userdata('account_type') == 'site_admin') {
				if($info['access']) {
					$query1 = $this->services_model->delete2($id);
					$query2 = $this->common_model->delete('services', $id);
				}
			} else {
				$query2 = false;
				
				if($info['access']) {
					$query1 = $this->services_model->delete2($id, $this->session->userdata('client_id'));
					$query2 = true;
				} else {
					$info2 = $this->common_model->getInfo('clients_services', $id, 'id', "service_id = $id AND client_id = " . $this->session->userdata('client_id'));

					if($info2) {
						$query1 = $this->services_model->delete2($id, $this->session->userdata('client_id'));
						$query2 = $this->common_model->delete('services', $id);
					}
				}
			}
			
			// Return results
			if($query1 && $query2) {
				//$this->logs_model->add($this->session->userdata("user_id"), 1, 0, 0, $this->session->userdata('post_id'), 'Deleted Announcement (' . $info['title'] . ')');
				echo "Deletion was successful.";
			} else {
				echo "Error deleting the selected row. Please try again later.";
			}
		} else {
			echo "This item does not exist in the database.";
		}
	}
	
	function getGlobalInfo() {
		global $data;
		
		// What to look for
		$id = $this->input->post('id');
		
		// Get information on this item
		$info = $this->common_model->getInfo($data['module'], $id);
		
		if($info) {
			$closing_codes = json_decode($info['closing_codes']);
			$codes = "";
					
			foreach($closing_codes as $code) {
				$codes .= $codes ? "\n$code" : $code;
			}
			
			$info['closing_codes'] = $codes;
			
			echo json_encode($info);
		}
	}
}